package com.easylinkin.linkappapi.mechanical.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.easylinkin.linkappapi.common.exceptions.BusinessException;
import com.easylinkin.linkappapi.common.model.RequestModel;
import com.easylinkin.linkappapi.device.constant.DeviceConstant;
import com.easylinkin.linkappapi.device.entity.Device;
import com.easylinkin.linkappapi.device.service.DeviceService;
import com.easylinkin.linkappapi.deviceattributestatus.controller.DeviceAttributeStatusController;
import com.easylinkin.linkappapi.deviceattributestatus.service.DeviceAttributeStatusService;
import com.easylinkin.linkappapi.mechanical.entity.Mechanical;
import com.easylinkin.linkappapi.mechanical.entity.MechanicalRefDevice;
import com.easylinkin.linkappapi.mechanical.service.IMechanicalRefDeviceService;
import com.easylinkin.linkappapi.project.entity.ProjectPoint;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import site.morn.rest.RestBuilders;
import site.morn.rest.RestMessage;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Date;
import java.util.List;


/**
 * 机械关联设备表 前端控制器
 *
 * @author xy
 * @since 2025-06-13
 */
@Api(tags = "机械关联设备表")
@RestController
@RequestMapping("/mechanical/mechanicalRefDevice")
public class MechanicalRefDeviceController {
    @Autowired
    private IMechanicalRefDeviceService mechanicalRefDeviceService;
    @Autowired
    private LinkappUserContextProducer linkappUserContextProducer;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private DeviceAttributeStatusService deviceAttributeStatusService;

    /**
     * 分页列表查询
     *
     * @param requestModel
     * @return
     */
    @ApiOperation(value="分页列表查询", notes="分页列表查询")
    @PostMapping(value = "/listPage")
    public RestMessage queryPageList(@RequestBody RequestModel<MechanicalRefDevice> requestModel) {
        // Assert.notNull(requestModel,"参数不能为空");
        // Assert.notNull(requestModel.getCustomQueryParams(), "customQueryParams 不能为空");
        Assert.notNull(requestModel.getPage(), "page 不能为空");
        if(CollUtil.isNotEmpty(requestModel.getSorts())){
            requestModel.getSorts().forEach(s -> {
                requestModel.getPage().getOrders().add(new OrderItem().setColumn(StrUtil.toUnderlineCase(s.getField())).setAsc("ASC".equalsIgnoreCase(s.getSortRule())));
            });
        }else{
            requestModel.getPage().getOrders().add(new OrderItem().setColumn("id").setAsc(false));
        }
        String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
        requestModel.getCustomQueryParams().setTenantId(tenantId);
        IPage<MechanicalRefDevice> pageList = mechanicalRefDeviceService.page(requestModel.getPage(), Wrappers.lambdaQuery(requestModel.getCustomQueryParams()));
        return RestBuilders.successBuilder().data(pageList).build();
    }

    /**
     * 保存
     *
     * @param mechanicalRefDevice
     * @return
     */
    @ApiOperation(value="保存", notes="保存")
    @PostMapping(value = "/save")
    public RestMessage save(@RequestBody MechanicalRefDevice mechanicalRefDevice) {
        setBase(mechanicalRefDevice);
        if(mechanicalRefDevice.getId() != null){
            mechanicalRefDevice.setModifyTime(new Date());
            mechanicalRefDeviceService.updateById(mechanicalRefDevice);
        } else{
            mechanicalRefDeviceService.save(mechanicalRefDevice);
        }
        return RestBuilders.successBuilder().message("保存成功" ).build();
    }

    /**
     * 设置基本属性
     *
     * @param mechanical
     */
    private void setBase(MechanicalRefDevice mechanical) {
        // 一个设备只能绑定一个机械
        MechanicalRefDevice oldMechanicalRefDevice = this.mechanicalRefDeviceService.getOne(Wrappers.<MechanicalRefDevice>lambdaQuery()
                .eq(MechanicalRefDevice::getDeviceId, mechanical.getDeviceId())
                .eq(MechanicalRefDevice::getTenantId, linkappUserContextProducer.getNotNullCurrent().getTenantId()));
        if(oldMechanicalRefDevice != null) {
            // 如果存在机械，则更新id，机械换绑设备
            mechanical.setId(oldMechanicalRefDevice.getId());
        }
        // 查询设备判断类型
        Device device = new  Device();
        device.setId(mechanical.getDeviceId());
        List<Device> deviceList = deviceService.selectDevices(device);
        if (CollUtil.isEmpty(deviceList)) {
            throw new BusinessException("关联的设备不存在");
        }
        Device device1 = deviceList.get(0);
        DeviceConstant.RailwayDeviceType railwayDeviceTypeByTypeId = DeviceConstant.RailwayDeviceType.getRailwayDeviceTypeByTypeId(device1.getDeviceTypeName());
        if (railwayDeviceTypeByTypeId == null) {
            throw new BusinessException("关联的设备类型不存在");
        }
        mechanical.setDeviceType(railwayDeviceTypeByTypeId.getRailDeviceTypeId());
        mechanical.setModifyTime(new Date());
        mechanical.setModifyId(linkappUserContextProducer.getCurrent().getId());
        //没有id就是新增,有就是编辑
        if (null == mechanical.getId()) {
            mechanical.setCreateId(linkappUserContextProducer.getCurrent().getId());
            mechanical.setCreateTime(new Date());
            mechanical.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
        }
    }

    /**
     * 解绑
     *
     * @param mechanicalRefDevice
     * @return
     */
    @ApiOperation(value="解绑", notes="解绑")
    @PostMapping(value = "/unbind")
    public RestMessage unbind(@RequestBody MechanicalRefDevice mechanicalRefDevice) {
        Assert.notNull(mechanicalRefDevice,"参数不能为空");
        Assert.notNull(mechanicalRefDevice.getDeviceId(), "deviceId 不能为空");
        Assert.notNull(mechanicalRefDevice.getRailMechanicalId(), "mechanicalId 不能为空");
        // 找到旧的绑定信息
        MechanicalRefDevice oldMechanicalRefDevice = this.mechanicalRefDeviceService.getOne(Wrappers.<MechanicalRefDevice>lambdaQuery()
                .eq(MechanicalRefDevice::getDeviceId, mechanicalRefDevice.getDeviceId())
                .eq(MechanicalRefDevice::getRailMechanicalId, mechanicalRefDevice.getRailMechanicalId())
                .eq(MechanicalRefDevice::getTenantId, linkappUserContextProducer.getNotNullCurrent().getTenantId()));
        if(oldMechanicalRefDevice == null) {
            return RestBuilders.errorBuilder().message("未找到对应绑定信息").build();
        }
        // 删除旧的
        oldMechanicalRefDevice.setModifyTime(new Date());
        oldMechanicalRefDevice.setModifyId(linkappUserContextProducer.getCurrent().getId());
        mechanicalRefDeviceService.updateById(oldMechanicalRefDevice);
        mechanicalRefDeviceService.removeById(oldMechanicalRefDevice.getId());
        return RestBuilders.successBuilder().message("解绑成功").build();
    }

    /**
     * 批量解绑
     *
     * @param mechanicalRefDevices
     * @return
     */
    @ApiOperation(value="批量解绑", notes="批量解绑")
    @PostMapping(value = "/unbindBatch")
    public RestMessage unbindBatch(@RequestBody List<MechanicalRefDevice> mechanicalRefDevices) {
        Assert.notEmpty(mechanicalRefDevices,"参数不能为空");
        // 找到旧的绑定信息
        for (MechanicalRefDevice mechanicalRefDevice : mechanicalRefDevices) {
            Assert.notNull(mechanicalRefDevice.getDeviceId(), "deviceId 不能为空");
            Assert.notNull(mechanicalRefDevice.getRailMechanicalId(), "mechanicalId 不能为空");
            // 找到旧的绑定信息
            MechanicalRefDevice oldMechanicalRefDevice = this.mechanicalRefDeviceService.getOne(Wrappers.<MechanicalRefDevice>lambdaQuery()
                    .eq(MechanicalRefDevice::getDeviceId, mechanicalRefDevice.getDeviceId())
                    .eq(MechanicalRefDevice::getRailMechanicalId, mechanicalRefDevice.getRailMechanicalId())
                    .eq(MechanicalRefDevice::getTenantId, linkappUserContextProducer.getNotNullCurrent().getTenantId()));
            if(oldMechanicalRefDevice != null) {
                // 删除旧的
                oldMechanicalRefDevice.setModifyTime(new Date());
                oldMechanicalRefDevice.setModifyId(linkappUserContextProducer.getCurrent().getId());
                mechanicalRefDeviceService.updateById(oldMechanicalRefDevice);
                mechanicalRefDeviceService.removeById(oldMechanicalRefDevice.getId());
            }
        }
        return RestBuilders.successBuilder().message("批量解绑成功").build();
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @ApiOperation(value="通过id删除", notes="通过id删除")
    @DeleteMapping(value = "/delete")
    public RestMessage delete(@RequestParam("id") Integer id) {
        mechanicalRefDeviceService.removeById(id);
        return RestBuilders.successBuilder().message("删除成功").build();
    }

    /**
     *  批量删除
     *
     * @param ids
     * @return
     */
    @ApiOperation(value="批量删除", notes="批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public RestMessage deleteBatch(@RequestParam("ids") String ids) {
        this.mechanicalRefDeviceService.removeByIds(Arrays.asList(ids.split(",")));
        return RestBuilders.successBuilder().message("批量删除成功").build();
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @ApiOperation(value="通过id查询", notes="通过id查询")
    @GetMapping(value = "/queryById")
    public RestMessage queryById(@RequestParam("id") Integer id) {
        MechanicalRefDevice mechanicalRefDevice = mechanicalRefDeviceService.getById(id);
        if(mechanicalRefDevice == null) {
            return RestBuilders.errorBuilder().message("未找到对应数据").build();
        }
        return RestBuilders.successBuilder().data(mechanicalRefDevice).build();
    }

    /**
     * 根据设备id和机械id 查询机械关联设备信息
     *
     * @param deviceId
     * @param mechanicalId
     * @return
     */
    @ApiOperation(value="根据设备id和机械id 查询机械关联设备信息", notes="根据设备id和机械id 查询机械关联设备信息")
    @GetMapping(value = "/queryByDeviceIdAndMechanicalId")
    public RestMessage queryByDeviceIdAndMechanicalId(@RequestParam("deviceId") Integer deviceId, @RequestParam("mechanicalId") Integer mechanicalId) {
        MechanicalRefDevice mechanicalRefDevice = this.mechanicalRefDeviceService.getOne(Wrappers.<MechanicalRefDevice>lambdaQuery()
                .eq(MechanicalRefDevice::getDeviceId, deviceId)
                .eq(MechanicalRefDevice::getRailMechanicalId, mechanicalId)
                .eq(MechanicalRefDevice::getTenantId, linkappUserContextProducer.getNotNullCurrent().getTenantId()));
        if(mechanicalRefDevice == null) {
            return RestBuilders.errorBuilder().message("未找到对应绑定信息").build();
        }
        return RestBuilders.successBuilder().data(mechanicalRefDevice).build();
    }

    /**
     * 根据机械id 查询机械关联设备信息
     *
     * @param mechanicalId
     * @return
     */
    @ApiOperation(value="根据机械id 查询机械关联设备信息", notes="根据机械id 查询机械关联设备信息")
    @GetMapping(value = "/queryByMechanicalId")
    public RestMessage queryByMechanicalId(@RequestParam("mechanicalId") String mechanicalId) {
        List<MechanicalRefDevice> mechanicalRefDevice = this.mechanicalRefDeviceService.list(Wrappers.<MechanicalRefDevice>lambdaQuery()
                .eq(MechanicalRefDevice::getRailMechanicalId, mechanicalId)
                .eq(MechanicalRefDevice::getTenantId, linkappUserContextProducer.getNotNullCurrent().getTenantId()));
        if(CollectionUtil.isEmpty(mechanicalRefDevice)) {
            return RestBuilders.errorBuilder().message("未找到对应绑定信息").build();
        }else{
            mechanicalRefDevice.forEach(mechanicalRefDevice1 -> {
                mechanicalRefDevice1.setLinkappAttributeStatusList(deviceAttributeStatusService.getLatestDeviceAttributeStatusList(mechanicalRefDevice1.getDeviceCode(), null));
            });
        }
        return RestBuilders.successBuilder().data(mechanicalRefDevice).build();
    }
}
